package xzy.com.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import xzy.com.config.jwt.annotation.PassToken;
import xzy.com.entity.domain.Loginfo;
import xzy.com.entity.domain.Users;
import xzy.com.entity.vo.Constant;
import xzy.com.entity.vo.ResponseBean;
import xzy.com.exception.CustomException;
import xzy.com.exception.CustomUnauthorizedException;
import xzy.com.service.LoginService;
import xzy.com.service.LoginfoService;
import xzy.com.util.JwtUtil;
import xzy.com.util.StringUtil;

@RestController
@RequestMapping("/api/login")
public class LoginController {
	@Resource
	private LoginService loginService;
	@Resource
	private LoginfoService loginfoService;

	@GetMapping("hello")
	public String hello() {
		return "hello springboot 启动成功！";
	}

	// 退出登录
	@PassToken
	@GetMapping("/loginout")
	public ResponseBean loginout(HttpSession session) {
		if (null != session.getAttribute("userInfo")) {
			session.removeAttribute("userInfo");
		}
		return new ResponseBean(HttpStatus.OK.value(), "退出成功！", null);
	}

	// 注册不需要token验证
	@PassToken
	@GetMapping("/userInfo")
	public ResponseBean userInfo(HttpSession session) {
		Users users=(Users) session.getAttribute("userInfo");
		return new ResponseBean(HttpStatus.OK.value(), "获取成功！", users);
	}

	// 注册不需要token验证
	@PassToken
	@PostMapping("/signin")
	public ResponseBean add(@RequestBody Users userDto) {
		// 判断当前帐号是否存在
		Users userDtoTemp = loginService.get(userDto);
		if (userDtoTemp != null && StringUtil.isNotBlank(userDtoTemp.getPassword())) {
			throw new CustomUnauthorizedException("该帐号已存在(Account exist.)");
		}
		userDto.setCreateTime(new Date());
		// 密码以帐号+密码的形式进行AES加密
		// 加密（账号+密码）
//		String key = AesCipherUtil.enCrypto(userDto.getPhone() + userDto.getPassword());
//		userDto.setPwd(key);//更新密码
		// userDto.setPassword(userDto.getPassword());
		int count = loginService.add(userDto);// 保存注册用户
		if (count <= 0) {
			throw new CustomException("新增失败(Insert Failure)");
		}

		return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", userDto);
	}

	// 登录
	@PostMapping("/login")
	public ResponseBean login(@RequestBody Users userDto, HttpServletResponse httpServletResponse,
			HttpServletRequest httpServletRequest, HttpSession session) {
		String account = userDto.getAccount();
		String password = userDto.getPassword();
		// 查询数据库中的帐号信息password
		Users userDtoTemp = new Users();
		System.out.println("用户登录" + account + ":" + password);
		userDtoTemp.setAccount(account);
		userDtoTemp = loginService.get(userDtoTemp);
		session.setAttribute("userInfo", userDtoTemp);

		if (userDtoTemp == null) {
			throw new CustomUnauthorizedException("该帐号不存在(The account does not exist.)");
		}
		if (userDtoTemp.getPassword().equals(password)) {
			String currentTimeMillis = String.valueOf(System.currentTimeMillis());
			// 从Header中Authorization返回AccessToken，时间戳为当前时间戳
			String token = JwtUtil.sign(account, currentTimeMillis);
			httpServletResponse.setHeader("Authorization", token);
			httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");

			// 添加登录日志
			Loginfo loginfo = new Loginfo();
			loginfo.setAccount(userDtoTemp.getAccount() + "-" + userDtoTemp.getUserName());
			loginfo.setIp(httpServletRequest.getRemoteAddr());// 获取ip地址
			loginfo.setLoginTime(new Date());
			loginfoService.save(loginfo);

			return new ResponseBean(HttpStatus.OK.value(), "登录成功(Login Success.)", token);
		} else {
			throw new CustomUnauthorizedException("帐号或密码错误(Account or Password Error.)");
		}
		// 密码进行AES解密
//		String key = AesCipherUtil.deCrypto(userDtoTemp.getPassword());
		// 因为密码加密是以帐号+密码的形式进行加密的，所以解密后的对比是帐号+密码
//		if (key.equals(account + password)) {
//			// 设置RefreshToken，时间戳为当前时间戳，直接设置即可(不用先删后设，会覆盖已有的RefreshToken)
//			String currentTimeMillis = String.valueOf(System.currentTimeMillis());
//			// 从Header中Authorization返回AccessToken，时间戳为当前时间戳
//			String token = JwtUtil.sign(account, currentTimeMillis);
//			httpServletResponse.setHeader("Authorization", token);
//			httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
//			return new ResponseBean(HttpStatus.OK.value(), "登录成功(Login Success.)", token);
//		} else {
//			throw new CustomUnauthorizedException("帐号或密码错误(Account or Password Error.)");
//		}

	}
}
